<template>
  <el-card class="w-full pt-[5px]">
    <div class="font-bold block-title">
      <!-- <el-icon class="mr-[5px]"><Plus /></el-icon> -->
      <el-icon class="mr-[5px] text-[#409EFF] align-middle" :size="26"><Tickets /></el-icon>自定义报表
    </div>
    <el-divider class="mt-2"/>
    <!-- <div class="line-view"></div> -->
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px">
      <el-row :gutter="20">
        <el-col :span="24">
          <!-- <el-form-item label="行表头：">
            <el-cascader ref="demoRef" :options="rowOptions" :props=" rowProps" :show-all-levels="false" v-model="rowVal" @change="demoChange" />
          </el-form-item> -->
          <el-form-item label="行表头："class="relative justify-start">
            <div class="cursor-pointer text-[#aeb1b0] pl-2.5 w-[80px] absolute left-0 top-0">请选择</div>
            <el-cascader ref="rowRef" :options="rowOptions" :props="rowProps" :show-all-levels="false" placeholder=" "
             v-model="rowVal" @change="rowChange"
            class="w-[214px] h-[30px] bg-transparent"
            />
            <div v-if="rowSelected.length>0" class="h-auto flex flex-1 flex-wrap">
              <span class="bg-gray-400 mx-2 mb-2 rounded-md h-[32px] text-white">
                <span class="px-2">{{ rowSelected[0].label || ''}}</span>                    
              </span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="rowSelected.length>0">
          <el-form-item label="列表头：" class="mb-[0px] relative justify-start" >
            <div class="cursor-pointer text-[#aeb1b0] pl-2.5 w-[80px] absolute left-0 top-0">请选择</div>
            <el-cascader :options="colOptions" :props="colProps" ref="colRef" :show-all-levels="false" placeholder=" "
              v-model="colVal" @change="colChange"
              class="w-[214px] h-[30px] bg-transparent"
              popper-class="el-style-reset"
            />
            <div class="h-auto flex flex-1 flex-wrap">
              <template v-for="(item, index) in colSelected" :key="index">
                <template v-if="item.children.length==0">  
                  <!-- 渲染最后一层 -->
                  <span :key="index" class="bg-gray-400 mx-2 mb-2 rounded-md h-[32px] text-white">
                    <span class="px-2">{{ item.label }}</span>
                    <el-select v-if="item.options&&item.options.length>0"
                      v-model="item.optionsVals"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      class="w-[191px] mt-[-3px] bg-blue-300"
                      placeholder="请选择"
                      @change="selectChange(item)"
                    >
                      <el-option v-for="item in item.options" :label="item.name" :value="item.name" />
                    </el-select>
                    <el-select v-if="item.data.isGroupbyYear == 1"
                      v-model="item.yearVals"
                      multiple
                      collapse-tags
                      collapse-tags-tooltip
                      placeholder="年份选择"
                      class="bg-white mt-[-3px]"
                      style="width: 141px"
                      @change="yearChange"
                    >
                      <el-option
                        v-for="item in yearOptions"
                        :key="item.value"
                        :label="`${item.label}年`"
                        :value="item.value"
                      />
                    </el-select>
                  </span>
                </template>
              </template>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mt-[15px]">
          <div class="flex justify-between">
            <el-form-item label="筛选条件">
              <el-button @click="searchConditionFlag = !searchConditionFlag"
                >
                <span>{{ !searchConditionFlag?"展开":"收起" }}</span>
                <el-icon color="#409EFF">
                  <CaretTop v-show="searchConditionFlag" />
                  <CaretBottom v-show="!searchConditionFlag" />
                </el-icon>
              </el-button>
              <el-button @click="clearCondition">清空</el-button>
            </el-form-item>
            <el-form-item >
              <el-button type="danger" @click="searchHandler"
                >
                <el-icon color="#fff" :size="19" class="mr-1">
                  <Search />
                </el-icon>
                <span class="text-xs">查询</span>
              </el-button>
              <el-button type="warning" @click="resetAll">
                <el-icon color="#fff" :size="19" class="mr-1">
                  <Refresh />
                </el-icon>
                <span class="text-xs">重置</span>
              </el-button>
              <!-- <el-button type="success"><el-icon color="#fff" :size="19" class="mr-1">
                  <CircleCheck />
                </el-icon>
                <span class="text-xs">保存配置</span>
              </el-button> -->
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-form-item label=" " v-show="searchConditionFlag">
        <el-row >
          <el-col :span="24">
            <el-form-item v-for="(item,index) in conditions" :label="item.name"  label-width="136px" :key="index">
              <el-select v-if="item.type =='select'" v-model="item.nameVal" placeholder="请选择" class="w-[141px]">
                <el-option v-for="ele in item.options" :label="ele.name || ele.label" :value="ele.name|| ele.label" :key="ele.name"/>
              </el-select>
              <el-input v-model="item.value" style="width: 141px" placeholder="请输入" />
              <template v-if="item.date">
                <el-date-picker v-model="item.dateRange" 
                value-format="YYYY-MM-DD"  type="daterange" 
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                style="width: 241px" @change="dateChange" />
              
                <!-- <el-date-picker
                  v-model="item.beginYear"
                  type="date"
                  placeholder="起始年份" @change="dateChange"
                />
                <el-date-picker
                  v-model="item.endYear"
                  type="date"
                  placeholder="结束年份" @change="dateChange"
                /> -->
              </template>
              <!-- <el-select v-model="searchForm.sex" placeholder="请选择" class="w-[241px]" >
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select> -->
              <span>
                <el-icon color="#409EFF" :size="26" class="ml-2" @click="addCondition(item,index)"><CirclePlusFilled /></el-icon>
                <el-icon color="rgb(177.3, 179.4, 183.6)" :size="26" class="ml-2" @click="removeCondition(index)"><RemoveFilled /></el-icon>
              </span>
            </el-form-item>      
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card class="w-full pt-[5px] mt-[10px] min-h-[140px]" v-loading="loading" element-loading-text="数据加载中...">
    <div v-if="tableData.length>0" class="mb-[20px] text-right">
      <el-button type="primary">
        <el-icon :size="20"><Download /></el-icon>
        <span class="text-xs">导出</span>
      </el-button>
    </div>
  <!-- 表头设置后，因为计算量不渲染 -->
    <el-table v-if="tableData.length>0" :data="tableData" class="min-[300px]">
      <el-table-column v-if="tableData.length>0" type="index" label="序号" width="50" align="center" />

      <template v-for="(item,ind) in tableColumn">
        <el-table-column v-if="!item.childFlag" :key="ind" :label="item.label" :prop="item.Field" align="center" :show-overflow-tooltip="true" />
        <template v-else >
          <el-table-column :key="ind" :label="item.label" :prop="item.Field" align="center" :show-overflow-tooltip="true">
            <el-table-column v-for="(second,ind2) in item.children" :key="`${ind}-${ind2}`" :label="second.label" :prop="second.Field" align="center" :show-overflow-tooltip="true" >
              <template v-if="second.childFlag">
                <el-table-column v-for="(third,ind3) in second.children" :key="`${ind}-${ind2}-${ind3}`" :label="third.label" :prop="third.Field" align="center" :show-overflow-tooltip="true" />
              </template>
            </el-table-column>
          </el-table-column>
        </template>  
      </template>
    </el-table>
    <div v-if="tableData.length==0" class="min-h-[140px] flex flex-col justify-center text-center text-gray-400">
      暂无数据！     
    </div>
    <!-- <div class="mt-[20px] flex justify-end">  -->
    <pagination v-show="tableData.length > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- </div> -->
  </el-card>
</template>

<script setup>
import { reactive, watch } from "vue"
import useAppStore from '@/store/modules/app'
import { zdyApi, getCategorys } from "@/api/statistics/index.js"
import { yearOptions, dealSecondColumnDataOld, dealYear } from "./index.js"
const { proxy } = getCurrentInstance();

// const router = useRouter();
// const appStore = useAppStore()

let dynamicData = {} //模拟数据
const rowProps = {
  label: 'name',
  value: 'id',
  children: 'children',
}
const colProps = { 
  multiple: true,
  emitPath: false,
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
}

const searchConditionFlag = ref(false);
const loading = ref(false);
const rowRef = ref()
const colRef = ref()
const rowVal = ref([])
const colVal = ref({})
const rowOptions = ref([])
const colOptions = ref([])
const rowSelected = ref([])
const colSelected = ref([])
const conditions = ref([
  // {
  //   name: parent.label,
  //   nameVal: "",
  //   id: parent.value,
  //   value: '',
  //   type: "input",
  //   dateRange: []
  // }
])
const tableColumn = ref([]);
const tableData = ref([]);
const total = ref(0);
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
});

const rowChange = (val) => {
  resetExcludeRow()
  rowSelected.value = rowRef.value.getCheckedNodes()
  // console.log("rowSelected:",rowSelected.value)
  getColOptions(rowSelected.value[0].data.columnTYPE)
}

const colChange = (val) => {
  loading.value = true;
  console.log("col变化时触发的事件--------------",val,colVal.value)
  if(val.length>5){
    proxy.$modal.msgWarning("最大可选5个选项")
    val.splice(5);

    colVal.value = []  // 选中项变化，只有清空选中项的值，再重新设置选中项才会触发渲染，否则 
    setTimeout(()=>{
      colVal.value = val // 回显选中数据
    },10)

    loading.value = false;
    return
  }

  // 列数据
  colSelected.value = colRef.value.getCheckedNodes()
  console.log("colSelected:",colSelected.value)
  if(colSelected.value.length===0){
    clearColSelected()
    loading.value = false;
  } else{
    getAndDealData()
  }
}
// 处理选项数据。同时要处理下拉select选择后的数据
const getAndDealData = ()=>{
  let columns = []
  dynamicData = {}
  try{
    // 生成行表头
    columns.push({
      id: 1, 
      label: rowSelected.value[0].label, 
      Field: rowSelected.value[0].data.nameLocal,
      childFlag: false
    })
    dynamicData[rowSelected.value[0].data.nameLocal] = rowSelected.value[0].label

    colSelected.value.forEach(async (item,index) => {
      const ind = index + 2
      // if(item.children.length===0){ //  children.length>0， 则不是最终节点，需要过滤掉  实际层级关联关系断开之后不存在该问题
        // 生成列表头
        let childObj = {
          id: ind, 
          label: item.label, 
          Field:item.data.nameLocal, 
          childFlag: false 
        }
        dynamicData[item.data.nameLocal] = item.label+"-1"
          
        //列表头包含下拉选项
        if(item.data.bizName){
          // 重新添加的表头项从接口获取数据
          if(!item.options || item.options.length===0){
            const res = await getCategorys({bizName: item.data.bizName})
            if(res.code === 200){
              item.options = res.data || []
            }
          }

          if(item.options && item.options.length>0){
            // 列表头 二级
            childObj.childFlag = item.options.length>0 ? true : false
            if(childObj.childFlag) {             
              childObj.children = dealSecondColumnDataOld(item,childObj,dynamicData)
            }
          }
          
          // const res = await getCategorys({bizName: item.data.bizName})
          // if(res.code === 200){
          //   item.options = res.data || []

          //   // 列表头 二级
          //   childObj.childFlag = item.options.length>0 ? true : false
          //   if(childObj.childFlag) {              
            //   childObj.children = dealSecondColumnDataOld(item,childObj,dynamicData)
          //   }
          // }      
        } else if(item.data.isGroupbyYear == 1){
          // 年选项 二级标题 
          if(item.yearVals && item.yearVals.length>0){           
            childObj.childFlag = true       
            childObj.children = dealYear(item,dynamicData) 
          }
        }

        // 生成列表头
        columns.push(childObj)
        
        // 检索条件
        if(item.parent !== undefined){
          const parent = item.parent || item
          const findInd = conditions.value.findIndex((x) => x.name === parent.label)
          if(findInd === -1){
            let obj = {
              name: parent.label,
              nameVal: "",
              id: parent.value,
              value: '',
              type: "input"
            }
            if(parent.data.children && parent.data.children.length>0){
              obj.type = "select"
              obj.options = parent.data.children
            }
            if(item.data.isGroupbyYear == 1){
              obj.date= true
            }
            conditions.value.push({
              ...obj
            })
          }
        }
        
      // }
    })

    // 清除检索条件中的移除的列表头项
    conditions.value.forEach(async (item,ind) => {   
      const findInd = colSelected.value.findIndex((x) => x.parent.value === item.id)
      if(findInd === -1){
        conditions.value.splice(ind,1)
      }
    })
    if(conditions.value.length==0){
      // clearColSelected()
      conditions.value = [];
    }
    
    // tableData.value = []
    tableColumn.value= columns
    setTimeout(() => {
      tableData.value = [dynamicData,dynamicData,dynamicData]
      total.value = 3
      loading.value = false;
      console.log("columns:",tableColumn.value)
      console.log("tableData:",tableData.value)
      console.log("conditions:",conditions.value)
      // console.log("colSelected:",colSelected.value)
    }, 1000);

  } catch(err){
    loading.value = false;
  }
}

// 筛选项后 重新处理数据
const dealSelectData = ()=>{
  dynamicData = {}
  let columns = []
  loading.value = true;
  try{
    // 生成行表头
    columns.push({
      id: 1, 
      label: rowSelected.value[0].label, 
      Field: rowSelected.value[0].data.nameLocal, 
      childFlag: false
    })
    dynamicData[rowSelected.value[0].data.nameLocal] = rowSelected.value[0].label

    colSelected.value.forEach(async (item,ind) => {
      // if(item.children.length===0){ //  children.length>0， 则不是最终节点，需要过滤掉  实际层级关联关系断开之后不存在该问题
        // 生成列表头
        let childObj = {
          id: ind, 
          label: item.label, 
          Field:item.data.nameLocal, 
          childFlag: false 
        }
        dynamicData[item.data.nameLocal] = item.label+"-1"

          
        //列表头包含下拉选项
         if(item.data.bizName){
        // if(item.options && item.options.length>0){
            // 列表头 二级
          childObj.childFlag = true
          childObj.children = dealSecondColumnDataOld(item,childObj,dynamicData)
        } else if(item.data.isGroupbyYear == 1){
          // 二级标题
          if(item.yearVals && item.yearVals.length>0){
            childObj.childFlag = true
            childObj.children = dealYear(item,dynamicData)
          }
        }
        // 生成列表头
        columns.push(childObj)

      // }
    })
    
    tableData.value = [] //解决清除列的子选项后 表头中依然存在最后一个清除项 。
    tableColumn.value= columns
    setTimeout(() => {
      // tableData.value = []
      tableData.value = [dynamicData,dynamicData,dynamicData]
      total.value = 3
      loading.value = false;
      console.log("columns:",tableColumn.value)
      console.log("tableData:",tableData.value)
      // console.log("conditions:",conditions.value)
      // console.log("colSelected:",colSelected.value)
    }, 1000);

  } catch(err){
    loading.value = false;
  }
}


const selectChange = (param) => {
  console.log(param)
  console.log(colSelected.value)
  dealSelectData();
};
const yearChange = (param) => {
  console.log(param)
  console.log(colSelected.value)
  dealSelectData();
};

// 筛选条件
const dateChange = (param) => {
  console.log(param,conditions.value)
};

const addCondition = (item,ind)=>{
  let obj = {
    name: item.name,
    value: "",
    type: "input"
  }
  if(item.options&&item.options.length>0){
    obj.type = "select"
    obj.options = item.options
  }
  if(item.date){
    obj.date= true
  }
  conditions.value.splice(ind+1,0,obj)
}
const removeCondition = (index)=>{
  //  数据重新组装，根据下标删除
  // const index = conditions.value.findIndex((x) => x.value === item.value)
  conditions.value.splice(index,1)
}

const searchHandler = ()=>{}

const clearColSelected = ()=>{
  tableColumn.value = [];
  tableData.value = [];
  conditions.value = [];
  // searchConditionFlag.value = false
}
const clearCondition = () => {
  console.log(conditions.value)
  conditions.value.forEach((item,index)=>{
    item.value = ""
    item.nameVal = ""
    if(item.date)item.dateRange = [];
  })
};

//重置
const resetAll = () => {
  rowVal.value = []
  rowSelected.value = []
  resetExcludeRow()
}
const resetExcludeRow = () => {
  colOptions.value = []
  colSelected.value = []
  tableColumn.value = []
  tableData.value = []
  // rowSelected.value = []
  // rowVal.value = []
  colVal.value = []
  total.value = 0
  conditions.value = []
  searchConditionFlag.value = false
  // history.go(0)
  // location.reload()
};

const recursion = (data)=>{
  data.forEach((item)=>{
    if(item.name== rowSelected.value[0].label) {
      item.disabled = true
    } else if(item.children && item.children.length>0){
      
      recursion(item.children)
    }
  })
}
const getRowOptions = async ()=>{
  const res = await zdyApi.getCustomstats()
  console.log(res)
  if(res.code == 200){
    rowOptions.value = res.data
    console.log(rowOptions.value)
  }
}
const getColOptions = async (columnTYPE)=>{
  colSelected.value = []
  const res = await zdyApi.fiveYHonorStats({columnTYPE: columnTYPE})
  console.log(res)
  if(res.code == 200){
    res.data.forEach((item,ind)=>{
      if(item.label == rowSelected.value[0].label){
        item.disabled = true
      } else if(item.children && item.children.length>0){
        item.disabled = true
        recursion(item.children)
      }
    })
    colOptions.value = res.data
  }
}
const setItem = (item)=>{
  let str = ''
  for(let i=0; i<item.length; i ++){
    
    if(i==0){
      str += item[i]
    } else{
      str +=  "/"+ item[i]
    }
  }
  return str
}
getRowOptions()
</script>

<style scoped lang="scss">
.block-title{
  color: #454545;
  // border-left: 7px solid #409EFF;
  // padding-left: 12px;
  height: 36px;
  display: block;
  line-height: 36px;
  .des-title{
    font-size: 14px;
    font-weight: 400;
    color: #b4b6bb;
  }
}
.line-view{
  width: 1920px;
  height: 6px;
  background: #3787FF;
  box-shadow: 0px 5px 20px 0px rgba(0,0,0,0.47);
  opacity: 0.24;
}

// 重构级联样式
::v-deep .el-form-item__content {
  align-items: start;
  flex-wrap: nowrap;
}
::v-deep .el-cascader__tags{
  height: 30px;  
  overflow: hidden;
  display: none; 
}
::v-deep .el-input__wrapper{
  background-color: transparent;
}
::v-deep .el-cascader .el-input {
  width: 214px;
}
::v-deep .el-cascader .el-input .el-input__inner {
  color: transparent;
}
</style>
<style>
.el-style-reset .el-checkbox.is-disabled {
  cursor: not-allowed;
  display: none !important;
}
</style>
